//
//  PaymentManager.m
//  WisdomZhuHai
//
//  Created by Admin on 14-11-3.
//  Copyright (c) 2014年 wyd. All rights reserved.
//

#import "PaymentManager.h"
#import "ProtocolManager.h"
#import "Common.h"
#import "PartnerConfig.h"
#import "DataSigner.h"
#import "AlixPayResult.h"
#import "DataVerifier.h"
#import "AlixPayOrder.h"
#import "AlixLibService.h"

@interface PaymentManager ()

@end

@implementation PaymentManager

PaymentManager *sharedPaymentManager = nil;

+ (PaymentManager*)shareInstance
{
    if (sharedPaymentManager == nil)
    {
        sharedPaymentManager = [[PaymentManager alloc] init];
    }
    return sharedPaymentManager;
}

- (void)startPay:(NSString*)payWayIdentifier withParams:(NSDictionary*)params fromViewController:(UIViewController*)viewController
{
    if ([payWayIdentifier isEqualToString:PAYWAY_IDENTIFIER_ALIPAY]) {
        [self payByAliPay:params];
    }
    else if ([payWayIdentifier isEqualToString:PAYWAY_IDENTIFIER_UPPAY]) {
        NSString* tn = [Common valueForKey:P_TN dic:params];
        [self payByUPPay:viewController tn:tn];
    }
}

#pragma mark - AliPay
- (void)payByAliPay:(NSDictionary*)params
{
    NSLog(@"payByAliPay");
    
    NSString *appScheme = @"okhaolvxing";
    NSString* orderInfo = [self getOrderInfo:params];
    NSString* signedStr = [self doRsa:orderInfo];
    
    NSLog(@"%@",signedStr);
    
    NSString *orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"", orderInfo, signedStr, @"RSA"];
	
    [AlixLibService payOrder:orderString AndScheme:appScheme seletor:@selector(AliPayResult:) target:self];
}

-(NSString*)getOrderInfo:(NSDictionary*)params
{
    AlixPayOrder *order = [[AlixPayOrder alloc] init];
    order.partner = PartnerID;
    order.seller = SellerID;
    
    order.tradeNO = [Common valueForKey:P_ORDERSN dic:params]; //订单ID（由商家自行制定）
	order.productName = [Common valueForKey:P_NAME dic:params]; //商品标题
	order.productDescription = [Common valueForKey:P_INTRO dic:params]; //商品描述
	order.amount = [NSString stringWithFormat:@"%.2f", [[Common valueForKey:P_ORDERPRICE dic:params] floatValue]]; //商品价格
	order.notifyURL = [NSString stringWithFormat:@"%@/%@", [ProtocolManager shareInstance].api_base_url, @"/Pay/alipayNotify"]; //回调URL
    order.returnUrl = [NSString stringWithFormat:@"%@/%@", [ProtocolManager shareInstance].api_base_url, @"/Pay/alipayResponse"];
	
	return [order description];
}

- (NSString*)doRsa:(NSString*)orderInfo
{
    id<DataSigner> signer;
    signer = CreateRSADataSigner(PartnerPrivKey);
    NSString *signedString = [signer signString:orderInfo];
    return signedString;
}

- (AlixPayResult *)resultFromURL:(NSURL *)url {
	NSString * query = [[url query] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	return [[AlixPayResult alloc] initWithString:query];
}

- (AlixPayResult *)handleOpenURL:(NSURL *)url {
	AlixPayResult * result = nil;
	
	if (url != nil && [[url host] compare:@"safepay"] == 0) {
		result = [self resultFromURL:url];
	}
    
	return result;
}

- (void)dealWithApiPayResult:(AlixPayResult*)result
{
    if (result.statusCode == 9000) {
        //交易成功
        NSString* key = AlipayPubKey;//签约帐户后获取到的支付宝公钥
        id<DataVerifier> verifier;
        verifier = CreateRSADataVerifier(key);
        
        if ([verifier verifyString:result.resultString withSign:result.signString]) {
            //验证签名成功，交易结果无篡改
            [self didPayCompleted:YES payStatus:[NSString stringWithFormat:@"%d", result.statusCode]];
        }
        else {
            [self didPayCompleted:NO payStatus:[NSString stringWithFormat:@"%d", result.statusCode]];
        }
    }
    else if (result.statusCode == 6001) {
        [self didPayCanceled:[NSString stringWithFormat:@"%d", result.statusCode]];
    }
    else {
        //交易失败
        [self didPayCompleted:NO payStatus:[NSString stringWithFormat:@"%d", result.statusCode]];
    }
}

#pragma mark - AliPay Call back
- (void)AliPayResult:(NSString*)result
{
    AlixPayResult* aliRes = [[AlixPayResult alloc] initWithString:result];
    [self dealWithApiPayResult:aliRes];
}

- (void)parse:(NSURL *)url
{
    //结果处理
    AlixPayResult* result = [self handleOpenURL:url];
    if (result != nil) {
        [self dealWithApiPayResult:result];
    }
}

#pragma mark - UPPay
- (void)payByUPPay:(UIViewController*)viewController tn:(NSString*)tn
{
    NSLog(@"payByUPPay");
#ifdef DEBUG
    NSString *mode = @"01";
#else
    NSString *mode = @"00";
#endif
    [UPPayPlugin startPay:tn mode:mode viewController:viewController delegate:self];
}

#pragma mark - UPPayPluginDelegate
- (void)UPPayPluginResult:(NSString*)result
{
    NSLog(@"UPPayPluginResult %@", result);
    if ([result isEqualToString:@"success"]) {
        [self didPayCompleted:YES payStatus:result];
    }
    else if ([result isEqualToString:@"cancel"]) {
        [self didPayCanceled:result];
    }
    else {
        [self didPayCompleted:NO payStatus:result];
    }
}

#pragma mark - Private
- (void)didPayCanceled:(NSString *)payStatus
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(didPayCanceled:)]) {
        [self.delegate didPayCompleted:NO payStatus:payStatus];
    }
}

- (void)didPayCompleted:(BOOL)ifSuccess payStatus:(NSString *)payStatus
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(didPayCompleted:payStatus:)]) {
        [self.delegate didPayCompleted:ifSuccess payStatus:payStatus];
    }
}

@end
